  (function() {
    'use strict';

    /**
     * @ngdoc function
     * @name webApp.controller:MainCtrl
     * @description
     * # MainCtrl
     * Controller of the webApp
     */
    angular.module('webApp')
        .controller('AddressCtrl', AddressCtrl);

    AddressCtrl.$inject = ['$scope', 'dataService','helper','sessionService','$location',"cacheService"];

    function AddressCtrl($scope, dataService,helper,sessionService,$location,cacheService) {
        $scope.address={};
    	$scope.initcity=function(){

        $("#city-picker").cityPicker({
		    toolbarTemplate: '<header class="bar bar-nav">\
		    <button class="button button-link pull-right close-picker">确定</button>\
		    <h1 class="title">选择收货地址</h1>\
		    </header>'
		  });
    	}
        $scope.addressAction=function(){
          $scope.buy_imdy=$location.search().buy_imdy;
          $scope.carts=$location.search().carts;

          var address_id= $location.search().address_id;
          var area_info=null;
          var area_info_activeIndex=[{activeIndex:0},{activeIndex:0},{activeIndex:0}];
          if(address_id){
             dataService.addressGet().then(function(result){
                _.map(result.deliver_addrs,function(addres){
                  if(addres.address_id==address_id){
                    $scope.address=addres;
                    if($scope.address.is_default==1){
                      $scope.is_default=true;
                    }
                    var init_area_info=$scope.address.area_info.split(" ");
                    // delete $scope.address.area_info;
                    var query={page_size:35,page_no:1};
                    query.query={parent_id:0}

                    dataService.areaGet(query).then(function(result){
                      if(result.Msg){

                      }else{
                        $scope.provinces=result.areas;
                        $scope.provinceIndex=0;
                        var provinces=[];
                        var province_id=null;
                        async.map($scope.provinces,function(province,callback){
                          provinces.push(province.area);
                          if(province.area==init_area_info[0]){
                            province_id=province.area_id;
                            area_info_activeIndex[0].activeIndex=$scope.provinceIndex;
                          }
                          $scope.provinceIndex++;
                          callback(null,null);
                        },function(e,r){
                           var cityQuery={page_no:1,page_size:300};
                            cityQuery.query={parent_id:province_id}
                            dataService.areaGet(cityQuery).then(function(citysResult){
                              $scope.citys=citysResult.areas;
                              var citys=[];
                              var city_id=null;
                              $scope.cityIndex=0;
                                async.map($scope.citys,function(city,call){
                                    citys.push(city.area);
                                    if(city.area==init_area_info[1]){
                                      city_id=city.area_id;
                                      area_info_activeIndex[1].activeIndex=$scope.cityIndex;
                                    }
                                    $scope.cityIndex++;
                                    call(null,null);
                                  },function(e,r){
                                       var countyQuery={page_no:1,page_size:300};
                                       countyQuery.query={parent_id:city_id};
                                       dataService.areaGet(countyQuery).then(function(countyResult){
                                        $scope.countys=countyResult.areas;
                                        var countys=[];
                                        $scope.countyIndex=0;
                                          async.map($scope.countys,function(county){
                                            countys.push(county.area);
                                            if(county.area==init_area_info[2]){
                                              area_info_activeIndex[2].activeIndex=$scope.countyIndex;
                                            }
                                            $scope.countyIndex++;
                                          });
                                          area_info = $("#area_info").picker({
                                            cols: [
                                              {
                                                textAlign: 'center',
                                                values: provinces,
                                                value:init_area_info[0]
                                              },{
                                                textAlign: 'center',
                                                values: citys,
                                                value:init_area_info[1]

                                              },{
                                                textAlign: 'center',
                                                values: countys,
                                                value:init_area_info[2]

                                              }
                                            ],
                                            onChange: area_info_change,
                                            onClose: area_info_close,
                                          });
                                       });
                                  });
                            });
                        });
                      }
                    });
                  }
                });
            });
          }else{
            var query={page_size:35,page_no:1};
            query.query={parent_id:0}
            dataService.areaGet(query).then(function(result){
              if(result.Msg){

              }else{
                $scope.provinces=result.areas;
                var provinces=[];
                var cityQuery={page_no:1,page_size:300};
                cityQuery.query={parent_id:$scope.provinces[0].area_id}
                dataService.areaGet(cityQuery).then(function(citysResult){
                  $scope.citys=citysResult.areas;
                  var citys=[];
                   var countyQuery={page_no:1,page_size:300};
                   countyQuery.query={parent_id:$scope.citys[0].area_id};
                   dataService.areaGet(countyQuery).then(function(countyResult){
                    $scope.countys=countyResult.areas;
                    var countys=[];
                     async.map($scope.provinces,function(province,callback){
                        provinces.push(province.area);
                        callback(null,null);
                      },function(e,r){
                       
                      });
                      async.map($scope.citys,function(city){
                        citys.push(city.area);
                      });
                      async.map($scope.countys,function(county){
                        countys.push(county.area);
                      });
                      area_info = $("#area_info").picker({
                        cols: [
                          {
                            textAlign: 'center',
                            values: provinces,
                          },{
                            textAlign: 'center',
                            values: citys,
                          },{
                            textAlign: 'center',
                            values: countys,
                          }
                        ],
                        onChange: area_info_change,
                        onClose: area_info_close,
                      });
                   });
                });
               
                
              }
            });
          }
           function area_info_change(p,v,d){
                if(area_info_activeIndex[0].activeIndex!=p.cols[0].activeIndex){
                  // if(index==0){
                    $scope.areainfoGet($scope.provinces[p.cols[0].activeIndex].area_id).then(function(result){
                      if(!result.Msg){
                        var citys=[];
                        $scope.citys=result;
                        if(result.length>0){
                          async.map(result,function(city,callback){

                            citys.push(city.area);
                            callback(null,null);
                          },function(e,r){
                              p.cols[1].replaceValues(citys,citys);
                              p.cols[1].activeIndex=0;
                              p.cols[1].displayValue=citys[0];
                              p.cols[1].value=citys[0]
                              $scope.areainfoGet($scope.citys[p.cols[1].activeIndex].area_id).then(function(rcountys){
                                   var countys=[];
                                    $scope.countys=rcountys;
                                    if(rcountys.length>0){
                                      async.map(rcountys,function(county,callback){
                                        countys.push(county.area);
                                        callback(null,null);
                                      },function(e,r){
                                           p.cols[2].replaceValues(countys,countys);
                                           p.cols[2].activeIndex=0;
                                           p.cols[2].displayValue=countys[0];
                                           p.cols[2].value=countys[0]
                                           // $("#area_info").picker("setValue", [p.cols[0].value, p.cols[1].value, p.cols[2].value])
                                           $scope.address.area_info=p.cols[0].value+" "+ p.cols[1].value+" "+ countys[0];
                                          
                                      });
                                    }else{
                                      p.cols[2].replaceValues(['--'],['--']);
                                      p.cols[2].activeIndex=0;
                                      p.cols[2].displayValue='--';
                                      p.cols[2].value='-';
                                      $scope.address.area_info=p.cols[0].value+" "+ p.cols[1].value+" "+ '--';
                                      $scope.countys=['--'];
                                    }
                              });
                          });
                        }else {
                          p.cols[1].replaceValues(['--'],['--']);
                          p.cols[1].activeIndex=0;
                          p.cols[1].displayValue='--';
                          p.cols[1].value='--';
                          p.cols[2].replaceValues(['--'],['--']);
                          p.cols[2].activeIndex=0;
                          p.cols[2].displayValue='--';
                          p.cols[2].value='-';
                          $scope.address.area_info=p.cols[0].value+" "+ '--'+" "+ '--';
                          $scope.citys=['--'];
                          $scope.countys=['--'];
                        }
                      }
                    });
                   area_info_activeIndex[0].activeIndex=p.cols[0].activeIndex;
                  }else if(p.cols[1].activeIndex&&area_info_activeIndex[1].activeIndex!=p.cols[1].activeIndex){

                  $scope.areainfoGet($scope.citys[p.cols[1].activeIndex].area_id).then(function(rcountys){
                      if(p.cols[1].activeIndex){


                         var countys=[];
                          $scope.countys=rcountys;
                          if(rcountys.length>0){
                            async.map(rcountys,function(county,callback){
                              countys.push(county.area);
                              callback(null,null);
                            },function(e,r){
                                 p.cols[2].replaceValues(countys,countys);
                                 // p.cols[2].displayValue=countys[0];
                                 // p.cols[2].value=countys[0];
                               // $("#area_info").picker("setValue", [p.cols[0].value, p.cols[1].value, countys[0]]);
                                $scope.address.area_info=p.cols[0].value+" "+ p.cols[1].value+" "+ countys[0];
                                area_info_activeIndex[1].activeIndex=p.cols[1].activeIndex;
                              
                            });
                          }else{
                            $scope.countys=['--'];
                            p.cols[2].replaceValues(['--'],['--']);
                            p.cols[2].activeIndex=0;
                            p.cols[2].displayValue='--';
                            p.cols[2].value='-';
                            $scope.address.area_info=p.cols[0].value+" "+ p.cols[1].value+" "+ '--';
                          }
                        }else{

                        }
                  });
                }
            }
            function area_info_close(p,v,d){
              $scope.address.city_id=$scope.citys[p.cols[1].activeIndex].area_id;
              $scope.address.area_id=$scope.countys[p.cols[2].activeIndex].area_id;
            }
        }
        $scope.areainfoGet=function(parent_id){
          var Query={page_no:1,page_size:300};
          Query.query={parent_id:parent_id};
          return  dataService.areaGet(Query).then(function(result){
              if(result.Msg){
                helper.myAlert("查询地址失败");
                $('#area_info').picker("close");
                return result;
              }else{
                return result.areas;
              }
          });
        }
      
        $scope.addAddress=function(){
          if($scope.is_default){
            $scope.address.is_default=1;
          }else{
            $scope.address.is_default=0;

          }
          if($scope.address.address_id){
             dataService.addressUpdate($scope.address).then(function(r){
                if(r.Msg){
                    helper.myAlert("error:"+r.Msg);
                }else{
                  // if($scope.addressAjaxStatus){
                  //   helper.myAlert("success","#/buy/add");

                  // }else{
                    helper.myAlert("success","#/address/list");

                  // }
                }
            });
          }else{
            // $scope.address.area_id=213;
            // $scope.address.member_id=sessionService.get("currentUserInfo").user_id;
            $scope.address.member_id=cacheService.get("currentUserInfo").user_id;
            // return false;
            // return false;
             dataService.addressAdd($scope.address).then(function(r){
                if(r.Msg){
                    helper.myAlert("error:"+r.Msg);
                }else{
                   if($scope.buy_imdy){
                    helper.myAlert("success","#/buy/choice?buy_imdy="+$scope.buy_imdy);

                  }
                 if($scope.carts){
                    helper.myAlert("success","#/buy/choice?cart="+$scope.carts);

                  }
                  if((!$scope.buy_imdy)&&(!$scope.carts)){
                    helper.myAlert("success","#/address/list");
                  }
                }
            });
          }
           
        }
        $scope.cancelAddress=function(){
          var url="";
            if($scope.buy_imdy){
                    url="#/buy/add?buy_imdy="+$scope.buy_imdy;

                  }
                 if($scope.carts){
                    url="#/buy/add?cart="+$scope.carts;
                  }
                  location.href=url;
        }
        $scope.defaultAddress=function(address){
          address.is_default=1;
          dataService.addressUpdate(address).then(function(result){
            if(result.Msg){
              helper.myAlert("error"+result.Msg);
            }else{
              _.map($scope.addresslist,function(addressItem){
                if(addressItem.address_id!=address.address_id){
                  addressItem.is_default=0;
                }
              });
            }
          });
        }
        $scope.addressListback=function(){
          var url="";
          if($scope.buy_imdy){
            url="#/buy/choice?buy_imdy="+$scope.buy_imdy;
          }else if($scope.carts){
            url="#/buy/choice?cart="+$scope.carts;
          }else{
            url="#/user/list";
          }
          location.href=url;
        }
        $scope.getAddressList=function(){
           $scope.buy_imdy=$location.search().buy_imdy;
          $scope.carts=$location.search().carts;
            dataService.addressGet().then(function(r){
                if(r.Msg){
                    helper.myAlert("error:"+r.Msg);
                }else{
                    $scope.addresslist=r.deliver_addrs
                }
            });
        }
        $scope.deleteAddress=function(address_id){
            dataService.addressDelete(address_id).then(function(r){
                if(r.Msg){
                    helper.myAlert("error:"+r.Msg);
                }else{
                    $scope.getAddressList();
                }
            })
        }
    }
})();